//
//  Google_History.m
//  MacStockApp
//
//  Created by 英傑 翁 on 12/3/21.
//  Copyright (c) 2012年 翁英傑. All rights reserved.
//
#import "XX_XQData_History.h"
#import "Google_History.h"
#import "GBTableColumnHeader.h"
#import "GBTableColumnHeader_basicSqlite.h"
#import "GBTableColumnHeader_quote.h"
#import "GBTableColumnHeader_2Row3Row.h"
#import "GBTableColumnHeader_node.h" 
#import "GBTableColumnHeader_position.h"  
#import "GBTableColumnHeader_position_bottom_sumaverage.h"  
#import "GBTableColumnHeader_Indicator.h"  
#import "GBTableColumnHeader_signal.h"  
#import "GBTableColumnHeader_ObjectOtherKey.h"  
#import "GBall.h"

@implementation Google_History
@synthesize delgeate;


-(id)init_With_Code:(NSString *)codea file_code:(NSString *)file_code table_quote_date:(NSDate *)dateq timezone:(NSString *)tz  is_have_to_reload_data:(BOOL)have_to_reload {
	
    if(self=[super init])
	{
        
        have_to_reload_data=have_to_reload;
        
        timezone=tz;  
        code=codea;
        read_write_file_code=file_code;
        table_quote_date=dateq;
        
        [code retain];
        [read_write_file_code retain];
        [table_quote_date retain];
        [timezone retain];        
    }
	
	return self;
}
 
-(void)dealloc{
    if (code) {
        [code release]; 
    }
    if (read_write_file_code) {
        [read_write_file_code release];
    }
    if (table_quote_date) {
        [table_quote_date release];
    }
    if (timezone) {
        [timezone release];
    }
  
    [super dealloc];
}

- (void)main 
{ 
    NSLog(@"XML_Bloomberg_History_main_his_Start=%@",code);
   
    if (have_to_reload_data) {
           
        NSMutableDictionary *out_dic; ;
        
               
        //取出歷史資料後的動作
        {
           
            //如果有xq資料
            if ([XX_XQData_History isHaveXQ_Dairly_Data:read_write_file_code]) {
                
                
                out_dic=[XX_XQData_History read_XQ_Dairly_Data:read_write_file_code _code:code _timezone:timezone];
                
                
                
            }
            else{
                
                //透過函數取出歷史資料相關資訊
                out_dic =[self get_history:40];
                
                //1.儲存檔案
                {
                    //歷史檔案路徑
                    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
                    NSString *Path_HistoryData  ;
                    Path_HistoryData=[prefs objectForKey:Defaults_Path_HistoryData];
                    
                    NSString *filename;
                    filename=[NSString stringWithFormat: @"%@.plist",read_write_file_code];
                    NSString * write_FilepathnName= [Path_HistoryData stringByAppendingPathComponent:filename]  ;
                    
                    
                    [out_dic writeToFile:write_FilepathnName atomically:YES];
                    
                }
                
            }
            
            
            
            
                       
            
            //2.將整理好的開收高低成交量資料傳出來 
            [(Data_Model *)delgeate performSelectorOnMainThread:@selector(His_Data_Finished:) withObject:out_dic waitUntilDone:YES];        
            
            //[out_dic release];    
        }    
        
        
    }
    else {
       
         NSMutableDictionary *out_dic=[[[NSMutableDictionary alloc] init] autorelease];
         
         [out_dic setObject:code forKey:DB_object_sqlite_basic_code];
          
         [(Data_Model *)delgeate performSelectorOnMainThread:@selector(His_Data_Finished_not_reload:) withObject:out_dic waitUntilDone:YES];
        
    }
    
        
    
    
}
 
-(NSMutableDictionary *)get_history: (int)download_year{
    
    //將代碼拆開
    NSArray *code_array;
    code_array = [code componentsSeparatedByString:@":"]   ;     
    
    if ([code_array count]==2) {
        
         
        //與除權息有關的:取出除權息資料
        NSMutableArray *split_divident_array;
        split_divident_array=[[[NSMutableArray alloc] init] autorelease];    
        {
              
            
            NSString *urls=[NSString stringWithFormat: @"http://www.google.com/finance?q=%@%%3A%@",[code_array objectAtIndex:1],[code_array objectAtIndex:0]] ;   
           
            //NSLog(@"%@ %@",[code_array objectAtIndex:1],[code_array objectAtIndex:0]);
            //NSLog(@"split_url=%@",urls);
            
            NSURL *  urla;
            urla = [NSURL URLWithString:urls];
            
            NSError * errorq = nil;
            NSString * download_string;
            download_string=[NSString stringWithContentsOfURL:urla encoding:NSUTF8StringEncoding error:&errorq];
            
            // NSLog(@"download_string=%@",download_string);
            
            //NSRange range_start = [download_string   rangeOfString:@"google.finance.data ="];            
            //NSRange range_end = [download_string rangeOfString:@"google.finance.data.numberFormat ="];             
            
            NSRange range_start = [download_string   rangeOfString:@"[{\\\"_quote\\\":"];            
            NSRange range_end = [download_string rangeOfString:@",related_items:"];             
            
            if (range_end.length>0 && range_start.length>0) {
                NSString *string2 = [download_string substringWithRange:NSMakeRange( range_start.location, range_end.location-range_start.location)];
                
                string2=[string2 stringByReplacingOccurrencesOfString:@"google.finance.data = " withString:@""]    ;        
                
                
                
                NSString *caa=    [[[[[ [[[ [[[[string2 stringByReplacingOccurrencesOfString:@"\\x27" withString:@"\'"] stringByReplacingOccurrencesOfString:@"\\x26" withString:@"&"] stringByReplacingOccurrencesOfString:@"\\x2" withString:@""] stringByReplacingOccurrencesOfString:@"\\x26F" withString:@""] stringByReplacingOccurrencesOfString:@"\\n" withString:@"="]  stringByReplacingOccurrencesOfString:@"\\" withString:@""] 
                                         stringByReplacingOccurrencesOfString:@"[" withString:@""] 
                                       stringByReplacingOccurrencesOfString:@"]" withString:@""]  
                                      stringByReplacingOccurrencesOfString:@"\"" withString:@""] stringByReplacingOccurrencesOfString:@"}" withString:@""]   stringByReplacingOccurrencesOfString:@"{" withString:@""] stringByReplacingOccurrencesOfString:@"_" withString:@""]           ; 
                
                
                
                NSArray * Timestamp_array=[caa  componentsSeparatedByString:@","]; 
                
                NSMutableDictionary *dic;
                dic= [[[NSMutableDictionary alloc] init] autorelease] ;          
                
                for (NSString *line in Timestamp_array  ) {
                    //NSString *code;
                    //NSLog(@"line=%@",line);   
                    
                    if ([line hasPrefix:@"quote:"])  {
                        NSString *codeaa;
                        codeaa=[line stringByReplacingOccurrencesOfString:@"quote:" withString:@""];
                       // NSLog(@"代碼:%@  ",code   );                 
                        
                        
                        dic= [[NSMutableDictionary alloc] init] ;
                        [dic setObject:codeaa forKey:@"code"];
                        
                        
                    }
                    
                    else if ([line hasPrefix:@"date:"]) {
                        NSString *dates;
                        dates=[line stringByReplacingOccurrencesOfString:@"date:" withString:@""];
                        
                        NSDate *start_time ;
                        start_time=[NSDate dateWithTimeIntervalSince1970:[dates intValue]  ];                 
                        
                        NSDateFormatter *start_dateFormatter = [[NSDateFormatter alloc] init];
                        [start_dateFormatter setTimeZone: [NSTimeZone   timeZoneWithName:timezone]];                        
                        start_dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm";  
                        //NSString *string_start_time = [start_dateFormatter stringFromDate:start_time];  
                        //NSLog(@"除息日date:%@  ",string_start_time   );
                        [start_dateFormatter release];                       
                        [dic setObject:start_time forKey:@"date"];                       
                        
                        
                    } 
                    else if ([line hasPrefix:@"type:"])  {
                        NSString *type ;
                        type=[line stringByReplacingOccurrencesOfString:@"type:" withString:@""];                     
                        
                        
                        [dic setObject:type forKey:@"type"]; 
                        
                        
                    }                    
                    
                    
                    
                    else if ([line hasPrefix:@"amount:"])  {
                        NSString *amount;
                        amount=[line stringByReplacingOccurrencesOfString:@"amount:" withString:@""];
                        //如果遇到股利 就是到最後
                        [dic setObject:amount forKey:@"amount"]; 
                        [split_divident_array addObject:dic];                  
                        [dic release];                 
                        
                    }
                    else if ([line hasPrefix:@"oldshares:"])  {
                        NSString *oldshares;
                        oldshares=[line stringByReplacingOccurrencesOfString:@"oldshares:" withString:@""];                     
                        
                        
                        [dic setObject:oldshares forKey:@"oldshares"]; 
                        
                        
                    }                       
                    else if ([line hasPrefix:@"newshares:"])  {
                        NSString *newshares;
                        newshares=[line stringByReplacingOccurrencesOfString:@"newshares:" withString:@""];                     
                        
                        //如果遇到股利 或是拆股 就是到最後
                        [dic setObject:newshares forKey:@"newshares"]; 
                        [split_divident_array addObject:dic]; 
                        [dic release];
                                    
                        
                    }                
                    
                    
                }
                
                /*
                for (NSDictionary  *dd in split_divident_array ) {
                     NSLog(@"aa=%@",dd);
                }
                */
                
            }
            
           
            
            
            
            
            
            
            
            
        }             
         


        //1.下載網址
        NSString *urls=[NSString stringWithFormat: @"http://www.google.com/finance/getprices?q=%@&x=%@&i=86400&p=%iY&f=d,c,v,o,h,l&df=cpct&auto=1&ts=1332125871951",[code_array objectAtIndex:1],[code_array objectAtIndex:0],download_year] ; 
        
        //NSLog(@"google urls=%@",urls);
        
        NSURL *  urla;
        urla = [NSURL URLWithString:urls];
        
        NSError * errorq = nil;
        NSString * download_string;
        //2.取出下載資料
        download_string=[NSString stringWithContentsOfURL:urla encoding: NSUTF8StringEncoding error:&errorq];
        // NSLog(@"download_string=%@",download_string);        
        
        NSArray *data_array=[download_string  componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
        
        int interval; //每個資料時間間隔
       // int timezone; //時區
        int start_NSDate ; //起頭時間
        
        
        
        interval=0;
       // timezone=0;
        start_NSDate=0;        
        
        BOOL issetHighLow;
        issetHighLow=NO;               
        
        NSMutableArray *outarray_his_data; //歷史資料
        outarray_his_data=[[[NSMutableArray alloc] init] autorelease];
        
        double his_data_high; // 最大值
        double his_data_low;  // 最小值 
        his_data_low=0;
        his_data_high=0;    
        
        NSDate *last_his_date=[NSDate dateWithTimeIntervalSince1970:9999];
        NSNumber *last_his_close=[NSNumber numberWithFloat: 0 ];        
        
        //依序取出每筆歷史資料
        for (NSString *line in data_array  ) {
            
            //每個index的間隔時間 理論上是
            if ([line hasPrefix:@"INTERVAL="]) {
                interval=[[line stringByReplacingOccurrencesOfString:@"INTERVAL=" withString:@""] intValue];
            }
            //時區
            else if ([line hasPrefix:@"TIMEZONE_OFFSET="]) {
               // timezone=[[line stringByReplacingOccurrencesOfString:@"TIMEZONE_OFFSET=" withString:@""] intValue];
            }  
            //起頭
            else if ( [line hasPrefix:@"COLUMNS=DATE"] ){
                
            }
            else if ( [line hasPrefix:@"DATA_SESSIONS"]){
                
            }
            else {
                
                NSArray *data_array;
                data_array = [line componentsSeparatedByString:@","]   ;                
                
                if ([data_array count]==6) {
                    NSMutableDictionary *dic;
                    dic=[[NSMutableDictionary alloc] init];                     
                    
                    NSDate *dates;
                    
                    
                    if ([[data_array objectAtIndex:0] hasPrefix:@"a"]  ) {
                        
                        start_NSDate= [[[data_array objectAtIndex:0] stringByReplacingOccurrencesOfString:@"a" withString:@""] intValue];
                        
                        dates=[NSDate dateWithTimeIntervalSince1970:start_NSDate  ];                          
                        
                    }
                    else {
                        dates=[NSDate dateWithTimeIntervalSince1970:start_NSDate +interval *[[data_array objectAtIndex:0] intValue] ];                         
                    }
                    
                    
                    //NSLog(@"date=%@",dates);
                    
                    //1:收盤
                    
                    //2:最高
                    
                    //3:最低
                    
                    //4.開盤
                    double d_close;
                    
                    double d_open;
                    double d_high;
                    double d_low;
                    
                    d_close=[[data_array objectAtIndex:1]  doubleValue ];                    
                    d_open=[[data_array objectAtIndex:4]  doubleValue];
                    d_low=[[data_array objectAtIndex:3]  doubleValue ];
                    d_high=[[data_array objectAtIndex:2]  doubleValue ];
                    if (d_low==0) {
                        d_low=d_close;
                    }
                    if (d_high==0) {
                        d_high=d_close;
                    }
                    if (d_open==0) {
                        d_open=d_close;
                    }
                    
                    NSNumber *close=[NSNumber numberWithDouble:d_close];
                    NSNumber *open=[NSNumber numberWithDouble:d_open];                               
                    NSNumber *high=[NSNumber numberWithDouble:d_high];                
                    NSNumber *low=[NSNumber numberWithDouble:d_low];                     
                    NSNumber *volume=[NSNumber numberWithInt:[[data_array objectAtIndex:5]  intValue ]];                    
                    
                    //比較取出歷史最大值與最小值
                    {
                        if (issetHighLow==NO) {
                            //第一次設定
                            his_data_low=[[data_array objectAtIndex:1] doubleValue ];
                            his_data_high=[[data_array objectAtIndex:1] doubleValue ];
                            issetHighLow=YES;
                        }
                        
                        if (d_high>his_data_high) {
                            his_data_high=d_high;
                        }
                        if (d_low<his_data_low  ) {
                            his_data_low=d_low;
                        }  
                        
                        
                        last_his_date=dates;
                        last_his_close=close;
                    }
                    
                    
                    
                    
                    [dic setObject:dates forKey: HIS_basic_date ];
                    [dic setObject:close forKey:HIS_basic_close];
                    [dic setObject:open forKey:HIS_basic_open];
                    [dic setObject:high forKey:HIS_basic_high];
                    [dic setObject:low forKey:HIS_basic_low];
                    [dic setObject:volume forKey:HIS_basic_vol];
                    [dic setObject:close forKey:HIS_basic_adjclose];                     
                     
                                        
                    
                    //NSLog(@"%@",line);                    
                    [outarray_his_data addObject:dic];
                    [dic release];                    
                    
                }
            }
            
            
            
        }
        
        //將股利除權資料存到歷史資料序列上
        for (NSMutableDictionary  *dd in split_divident_array ) {
            //NSLog(@"股利息資料=%@",dd);
            
            int indxs;
            indxs=[self index_split_array:outarray_his_data nsdate:[dd objectForKey:@"date"]];
            // NSLog(@"股利息資料=%i",indxs);
            
            if (indxs>=0) {
                //先扣掉息
                if ([[dd objectForKey:@"type"] isEqualToString:@"dividend"]) {
                    
                    double divident;
                    divident=[[dd objectForKey:@"amount"] doubleValue];
                    
                    [[outarray_his_data objectAtIndex:indxs] setObject:[NSNumber numberWithDouble:divident] forKey:HIS_basic_dividend];                            
                    //還息計算方式
                    for (int i=0; i<indxs; i++) {
                        double adjclose;
                        adjclose=[[[outarray_his_data objectAtIndex:i] objectForKey:HIS_basic_adjclose] doubleValue];
                       
                        adjclose=adjclose-divident;
                        
                        [[outarray_his_data objectAtIndex:i] setObject:[NSNumber numberWithDouble:adjclose] forKey: HIS_basic_adjclose] ;     
                        
                        
                    }
                    
                    
                }
                //在還權
                if([[dd objectForKey:@"type"] isEqualToString:@"split"]) {
                    
                    int oldshares;
                    int newshares;
                    oldshares=[[dd objectForKey:@"oldshares"] doubleValue];
                    newshares=[[dd objectForKey:@"newshares"] doubleValue];   
                    
                    
                    [[outarray_his_data objectAtIndex:indxs] setObject:[NSNumber numberWithInt:oldshares] forKey:HIS_basic_oldshares]; 
                    [[outarray_his_data objectAtIndex:indxs] setObject:[NSNumber numberWithInt:newshares] forKey:HIS_basic_newshares];   
                    //還權計算方式
                    for (int i=0; i<indxs; i++) {
                        double adjclose;
                        adjclose=[[[outarray_his_data objectAtIndex:i] objectForKey:HIS_basic_adjclose] doubleValue];
                        
                        adjclose=adjclose*oldshares/newshares;
                        
                        [[outarray_his_data objectAtIndex:i] setObject:[NSNumber numberWithDouble:adjclose] forKey: HIS_basic_adjclose] ;     
                        
                        
                    }                    
                    
                }
                
                
            }
            
            
        }              
         
        //將歷史資料檔案陣列 最大值 最小值 存放在Dictionary，用來傳出去
        NSMutableDictionary *out_dic=[[[NSMutableDictionary alloc] init] autorelease];
        [out_dic setObject:code forKey:DB_object_sqlite_basic_code];
        [out_dic setObject:outarray_his_data forKey:@"his_data"];
        [out_dic setObject:[NSNumber numberWithDouble: his_data_high] forKey:@"his_data_high"];
        [out_dic setObject:[NSNumber numberWithDouble: his_data_low] forKey:@"his_data_low"];      
        [out_dic setObject:last_his_date forKey:@"last_his_date"];
        [out_dic setObject:last_his_close forKey:@"last_his_close"]; 
        
                
        return out_dic;
        
    }
    else {
        return  nil;
    }
    
    
}
 
#pragma mark -
#pragma mark 除權息相關

//輸入日期 取出相同日期的位置 單筆
-(NSUInteger)index_split_array:(NSMutableArray *)split_array nsdate:(NSDate *)findate {
    
    
    NSUInteger idx = [ split_array  indexOfObjectPassingTest:
                      ^ BOOL (NSMutableDictionary* obj, NSUInteger idx, BOOL *stop)
                      {
                          BOOL result =[self isSameDay:[ obj  objectForKey:HIS_basic_date]  date2:findate];                           
                          *stop = result;
                          return result;                                      
                          
                      }];                
    
    return idx;
    
    
    
}

//輸入日期 取出相同日期的位置陣列 多筆
-(NSMutableArray*)indexs_split_array:(NSMutableArray *)split_array nsdate:(NSDate *)findate {
     
    NSMutableArray *out_indexs;
    out_indexs=[[[NSMutableArray alloc] init] autorelease];
    
    for (int i=0 ; i<[split_array count]; i++) {
        NSDictionary * dic =[split_array objectAtIndex:i];
        if ([self isSameDay:[ dic  objectForKey:@"date"]  date2:findate]) {
            [out_indexs addObject:[NSNumber numberWithInt:i]];
        }        
    }
     
    return out_indexs;
     
}
 
//比較兩個日期是否為同一個交易日
- (BOOL)isSameDay:(NSDate*) date1  date2:(NSDate *) date2 {
    NSCalendar* calendar = [NSCalendar currentCalendar];
    
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];
    
    return [comp1 day]   == [comp2 day] &&
    [comp1 month] == [comp2 month] &&
    [comp1 year]  == [comp2 year];    
    
}




 
@end
